<template>
  <div class="main">
    <el-form inline label-width="120px" style="display: flex">
      <el-form-item label="文件名">
        <el-input v-model="filename" />
      </el-form-item>
      <el-form-item label="文件类型">
        <el-select v-model="fileType">
          <el-option
            v-for="item in fileTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="">
        <el-button type="primary" @click="handleDownloadExecl">导出选中的数据</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="tableData" border @selection-change="selectionChange">
      <el-table-column type="selection" />
      <el-table-column prop="id" label="ID" />
      <el-table-column prop="name" label="用户名" />
      <el-table-column prop="age" label="年龄" sortable />
      <el-table-column prop="address" label="地址" />
    </el-table>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue'
import { formatJson } from '@/utils'
import { exportJson2Excel } from '@/utils/excel'
interface User {
  id: number
  name: string
  age: number
  address: string
}

export default defineComponent({
  name: 'execl',
  setup() {
    const tableData = ref<User[]>([])
    const queryTableData = () => {
      const str = '巩俐,刘诗诗,董洁,刘亦菲,许晴,蒋勤勤,刘涛,秦海璐,高圆圆,周海媚,张曼玉,赵丽颖,杨幂,张子怡,汤唯,周迅,陈红,陶红,俞飞鸿,林心如,马伊琍,杨紫,张静初,古力娜扎,陈乔恩,蔡少芬,宋茜,宋佳,王丽坤,马思纯,舒淇,李若彤,刘嘉玲,倪妮,颜丙燕,唐嫣,景甜,关小彤,李小冉,梅婷,李嘉欣,迪丽热巴,周冬雨,赵雅芝,林青霞,王祖贤,佟丽娅,海清'
      const keys = str.split(',')
      tableData.value = keys.map((name, index) => {
        return {
          id: index,
          name,
          age: Math.round(Math.random() * 32) + 18, // 生成18到50
          address: '北京市朝阳区天安门1号'
        }
      })
    }
    queryTableData()
    return {
      tableData,
      queryTableData
    }
  },
  data() {
    return {
      filename: 'download',
      fileType: 'xlsx',
      fileTypeList: [
        { label: 'xlsx', value: 'xlsx' },
        { label: 'csv', value: 'csv' },
        { label: 'txt', value: 'txt' }
      ],
      selection: [] as User[]
    }
  },
  methods: {
    handleDownloadExecl() {
      const tHeader = ['ID', '用户名', '年龄', '地址']
      const filterVal = ['id', 'name', 'age', 'address']
      const list = this.selection.length > 0 ? this.selection : this.tableData
      const data = formatJson(filterVal, list)
      exportJson2Excel(tHeader, data, this.filename !== '' ? this.filename : undefined, [], [], true, this.fileType)
    },
    selectionChange(selection: User[]) {
      this.selection = selection
    }
  }
})
</script>

<style lang="scss" scoped>

</style>
